//
//  HLEAppDelegate.m
//  RPCFCADemo
//
//  Created by john on 10/18/2022.
//  Copyright (c) 2022 john. All rights reserved.
//
#include <sys/sysctl.h>
#import "HLEAppDelegate.h"
#import "QMUIKit.h"
//#import <DoraemonKit/DoraemonManager.h>
#import "HLEViewController.h"
#import <Bugly/Bugly.h>
#import "RPDBManage.h"
#import "RPNetworkUitls.h"



@implementation HLEAppDelegate

-(void)startApplication:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    [self.window makeKeyAndVisible];
    self.window.backgroundColor = [UIColor whiteColor];
    HLEViewController *vc = [[HLEViewController alloc] init];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    self.window.rootViewController = nav;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    void (^name)(void) = ^() {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [QMUITips showError:@"APP被反调试了" inView:kAppWindow hideAfterDelay:2];
        });
    };
    
    // Override point for customization after application launch.
    [Bugly startWithAppId:@"f627891199"];
    //
    BOOL jjjj = [self ahhddfdsfsdfsdfsdf];
    if(jjjj) {
        name();
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            exit(0);
        });
    }
    __unused RPDBManage *object  = RPDBManage.share;
    
    [[self secureInitial] then:^id _Nullable(NSDictionary * dic) {
        NSString * policy_number_value = [NSString stringWithFormat:@"%@",dic[@"policy_number"]];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *policyNumber = [defaults objectForKey:@"policy_number"];
        if (policyNumber == nil) {
            // 本地不存在policy_number
        } else {
            // 本地存在policy_number，进行处理
            if(![policyNumber isEqualToString:policy_number_value]){
                [RPDBManage.share deleteData];
                [NSUserDefaults.standardUserDefaults setInteger:1 forKey:@"currentUser"];
                [self alert:^{
                    
                }];
            }
        }
        [defaults setObject:policy_number_value forKey:@"policy_number"];
        return nil;
    }];

#if 1
    RPDataManager.sharedInstance.company = @"SHNNSH";
    RPDataManager.sharedInstance.organ = @"NSH";
    RPDataManager.sharedInstance.url = @"101.230.91.32";
    RPDataManager.sharedInstance.port = @"8882";
    RPDataManager.sharedInstance.acount = @"R1";
    
//    RPDataManager.sharedInstance.company = @"CYFX";
//    RPDataManager.sharedInstance.organ = @"SZHQ";
//    RPDataManager.sharedInstance.url = @"121.4.208.208";
//    RPDataManager.sharedInstance.port = @"843";
//    RPDataManager.sharedInstance.acount = @"admin";
#else
    RPDataManager.sharedInstance.company = @"QYSK";
    RPDataManager.sharedInstance.organ = @"ABC";
    RPDataManager.sharedInstance.url = @"192.168.1.126";
    RPDataManager.sharedInstance.port = @"8443";
    RPDataManager.sharedInstance.acount = @"admin";
#endif

//    [QMUIConsole sharedInstance].canShow = YES;
//    [[DoraemonManager shareInstance] installWithPid:@"productId"];//productId为在“平台端操作指南”中申请的产品id
//    [BCJPrivateProtocolAlert showWithModel:[ BJCPrivateProtocolModel new ] block:^{
//        [self startApplication:application didFinishLaunchingWithOptions:launchOptions];
//    } ];
    [self startApplication:application didFinishLaunchingWithOptions:launchOptions];
    
//    if (UIDevice.currentDevice.isJailbroken || UIDevice.currentDevice.isSimulator) {
//        UIWindow *window = [UIApplication sharedApplication].keyWindow;
//        [QMUITips showError:@"环境异常，即将推出" inView:window hideAfterDelay:2];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            exit(0);
//        });
//    }
    
    [self alert:^{
        
    }];
    
    return YES;
}



- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (FBLPromise <NSDictionary *>*)secureInitial
{
    return [FBLPromise onQueue:dispatch_get_main_queue() async:^(FBLPromiseFulfillBlock  _Nonnull fulfill, FBLPromiseRejectBlock  _Nonnull reject) {
        AFHTTPSessionManager *manager = [RPNetworkUitls getNetworkManager];
//        @"https://121.4.208.208:843/secureTime"
//        RPCsecureMobile
        [manager POST:RPCSecureInitial parameters:@{} headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:NULL];
            fulfill(dic);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"====:%@",error),
            reject(error);
        }];
    }];
}



/**
 *  如果当前进程正在调试则返回true
 */
- (BOOL)ahhddfdsfsdfsdfsdf {
    int                 junk;
    int                 mib[4];
    struct kinfo_proc   info;
    size_t              size;

    info.kp_proc.p_flag = 0;
 
 
    mib[0] = CTL_KERN;
    mib[1] = KERN_PROC;
    mib[2] = KERN_PROC_PID;
    mib[3] = getpid();
 

 
    size = sizeof(info);
    junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
    assert(junk == 0);
    

    return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
}

- (void)alert:(void (^)(void))block {
    NSInteger flag = [NSUserDefaults.standardUserDefaults integerForKey:@"currentUser"];
    if (flag != 2) {
        [NSUserDefaults.standardUserDefaults removeObjectForKey:BCJPrivateProtocolAlertDefaultsKey];
        [BCJPrivateProtocolAlert showWithModel:[ BJCPrivateProtocolModel new ] block:^{
            [NSUserDefaults.standardUserDefaults setInteger:2 forKey:@"currentUser"];
            [NSUserDefaults.standardUserDefaults synchronize];
            block();
        }];
    }else{
        block();
    }
}


@end
